<template>
  <div class="element-management">
    <!-- 页面标题栏 -->
    <div class="page-header">
      <h1 class="page-title">元素设置管理</h1>
      <div class="header-info">
        <span class="breadcrumb">首页 / 基础设施 / 元素设置</span>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧分类 -->
      <div class="sidebar">
        <h3 class="sidebar-title">元素分类</h3>
        <el-menu 
          :default-active="activeCategory" 
          @select="handleCategoryChange" 
          class="category-menu"
        >
          <el-menu-item index="0">患者基本属性</el-menu-item>
          <el-menu-item index="1">体征元素</el-menu-item>
          <el-menu-item index="2" style="background-color: #e6f2ff; color: #1a5276; font-weight: bold;">病史元素</el-menu-item>
          <el-menu-item index="3">随访表元素</el-menu-item>
          <el-menu-item index="4">调查问卷元素</el-menu-item>
          <el-menu-item index="5">评估表元素</el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧内容 -->
      <div class="content-panel">
        <!-- 搜索和操作区 -->
        <el-card class="search-card" shadow="hover">
          <!-- 搜索 -->
          <div class="search-section">
            <el-input 
              v-model="page.ElementName" 
              placeholder="元素名称" 
              clearable 
              size="small" 
              class="search-input"
              prefix-icon="el-icon-search"
            />
            <el-select 
              v-model="page.Elementalform" 
              placeholder="状态" 
              size="small" 
              class="search-select"
            >
              <el-option label="全部" :value="null" />
              <el-option label="启用" :value="true" />
              <el-option label="停用" :value="false" />
            </el-select>
            <div class="search-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click="list"
                icon="el-icon-search"
                class="search-btn"
              >查询</el-button>
              <el-button 
                size="small" 
                @click="resetSearch"
                icon="el-icon-refresh"
                class="reset-btn"
              >重置</el-button>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button 
              type="primary" 
              size="small" 
              @click="showCreateDialog"
              icon="el-icon-plus"
              class="create-btn"
            >+ 新建</el-button>
            <el-button 
              type="success" 
              size="small"
              icon="el-icon-check"
              class="enable-btn"
            >启用</el-button>
            <el-button 
              type="warning" 
              size="small"
              icon="el-icon-pause"
              class="disable-btn"
            >停用</el-button>
            <el-button 
              type="danger" 
              size="small"
              icon="el-icon-delete"
              class="delete-btn"
            >删除</el-button>
          </div>
        </el-card>

        <!-- 表格 -->
        <el-card class="table-card" shadow="hover">
          <el-table 
            :data="tableData" 
            stripe 
            border 
            style="width: 100%;" 
            row-key="elementId"
            :header-cell-style="headerCellStyle"
            :row-class-name="tableRowClassName"
            empty-text="暂无数据"
          >
            <el-table-column 
              prop="elementNum" 
              label="元素类别" 
              width="120"
              align="center"
            />
            <el-table-column 
              prop="elementCode" 
              label="元素代码" 
              width="100"
              align="center"
            />
            <el-table-column 
              prop="elementName" 
              label="元素名称" 
              min-width="200"
            />
            <el-table-column 
              prop="elementalAbbreviation" 
              label="元素简码" 
              width="120"
              align="center"
            />
            <el-table-column 
              prop="elementType" 
              label="元素类型" 
              width="120"
              align="center"
            />
            <el-table-column 
              prop="elementalform" 
              label="状态" 
              width="80"
              align="center"
            >
              <template #default="{ row }">
                <el-tag 
                  :type="row.elementalform ? 'primary' : 'warning'"
                  effect="light"
                >
                  {{ row.elementalform ? '启用' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column 
              label="操作" 
              width="120"
              align="center"
            >
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  link 
                  size="small" 
                  @click="handleEdit(row)"
                  class="edit-link"
                >编辑</el-button>
                <el-button 
                  type="danger" 
                  link 
                  size="small"
                  class="delete-link"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="page.pageIndex"
              v-model:page-size="page.pageSize"
              :total="page.totalCount"
              :page-sizes="[5, 10, 15, 20]"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              prev-text="上一页"
              next-text="下一页"
              @size-change="list"
              @current-change="list"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEditing ? '编辑元素' : '新建元素'" 
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form 
        :model="formData" 
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="元素类别:" :required="true">
          <el-select 
            v-model="formData.elementCategory" 
            placeholder="请选择" 
            style="width: 100%;"
          >
            <el-option 
              v-for="item in categories" 
              :key="item.elementtypeId"
              :label="item.elementNum"
              :value="item.elementtypeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="元素代码:" :required="true">
          <el-input v-model="formData.elementCode" placeholder="请输入元素代码" />
        </el-form-item>
        <el-form-item label="元素名称:" :required="true">
          <el-input v-model="formData.elementName" placeholder="请输入元素名称" />
        </el-form-item>
        <el-form-item label="元素简码:">
          <el-input v-model="formData.elementalAbbreviation" placeholder="请输入元素简码" />
        </el-form-item>
        <el-form-item label="元素类型:" :required="true">
          <el-select v-model="formData.elementType" style="width: 100%;">
            <el-option label="平铺单选" value="平铺单选" />
            <el-option label="下拉选择" value="下拉选择" />
            <el-option label="文本输入" value="文本输入" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用:">
          <el-switch v-model="formData.elementalform" active-text="启用" inactive-text="停用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleSave" class="save-btn">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 接口定义
interface ElementData {
  elementId: string | null
  elementNum: string
  elementCode: string
  elementName: string
  elementalAbbreviation: string
  elementType: string
  elementalform: boolean
  elementtypeId?: number | null
  isDel?: boolean
  elementCategory?: number | null
}

interface CategoryData {
  elementtypeId: number
  elementNum: string
}

interface PageParams {
  pageIndex: number
  pageSize: number
  ElementName: string
  Elementalform: boolean | null
  totalCount: number
  ElementCategory: number | null
}

// 数据
const tableData = ref<ElementData[]>([])
const categories = ref<CategoryData[]>([])
const dialogVisible = ref(false)
const isEditing = ref(false)
const activeCategory = ref('2')

// 分页参数
const page = reactive<PageParams>({
  pageIndex: 1,
  pageSize: 5,
  ElementName: '',
  Elementalform: null,
  totalCount: 0,
  ElementCategory: null, // 用于过滤分类
})

// 表单数据
const formData = reactive<ElementData>({
  elementId: null,
  elementNum: '',
  elementtypeId: null,
  elementCode: '',
  elementName: '',
  elementalAbbreviation: '',
  elementType: '',
  elementalform: true,
  isDel: true,
  elementCategory: null,
})

// 表格头部样式
const headerCellStyle = {
  backgroundColor: '#f5f7fa',
  fontWeight: 600,
  color: '#1f2937',
  textAlign: 'center'
}

// 表格行样式
const tableRowClassName = ({ rowIndex }: { rowIndex: number }): string => {
  return rowIndex % 2 === 0 ? 'table-row-even' : 'table-row-odd'
}

// 获取数据
const list = async () => {
  try {
    const res = await axios.get('http://localhost:5108/api/Manager/ElementShow', { params: page });
    // 添加安全检查
    if (res.data && res.data.data) {
      tableData.value = res.data.data.data || [];
      page.totalCount = res.data.data.totalCount || 0;
    } else {
      throw new Error('数据格式不正确');
    }
  } catch (error) {
    // console.error('获取数据失败:', error);
    // ElMessage.error('获取数据失败，请稍后重试');
    // 提供模拟数据用于演示
    tableData.value = getMockData();
    page.totalCount = tableData.value.length;
  }
}

// 获取分类
const listCategory = async () => {
  try {
    const res = await axios.get('http://localhost:5108/api/Manager/SelectElement');
    // 添加安全检查
    if (res.data && Array.isArray(res.data.data)) {
      categories.value = res.data.data;
    } else {
      categories.value = [];
    }
  } catch (error) {
    // console.error('获取分类失败:', error);
    // ElMessage.error('获取分类失败，请稍后重试');
    categories.value = [];
  }
}

// 重置搜索
const resetSearch = () => {
  page.ElementName = '';
  page.Elementalform = null;
  page.pageIndex = 1;
  page.ElementCategory = null;
  list();
}

// 显示弹窗
const showCreateDialog = () => {
  isEditing.value = false
  // 重置表单
  formData.elementId = null
  formData.elementtypeId = parseInt(activeCategory.value)
  formData.elementCode = ''
  formData.elementName = ''
  formData.elementalAbbreviation = ''
  formData.elementType = ''
  formData.elementalform = true
  formData.isDel = true
  formData.elementCategory = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: ElementData) => {
  isEditing.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 保存
const handleSave = async () => {
  // 简单验证
  if (!formData.elementName || !formData.elementCode) {
    ElMessage.warning('请填写必要的元素名称和代码');
    return;
  }
  
  const url = isEditing.value 
    ? `http://localhost:5203/api/Managment/ElementPut`
    : 'http://localhost:5203/api/Managment/ElementAdd'
    
  const method = isEditing.value ? 'put' : 'post'
  
  try {
    await axios[method](url, formData);
    ElMessage.success('保存成功');
    dialogVisible.value = false;
    list();
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请稍后重试');
  }
}

// 切换分类
const handleCategoryChange = (index: string) => {
  activeCategory.value = index
  page.ElementCategory = parseInt(index) || null // 设置分类ID，确保转换失败时为null
  page.pageIndex = 1 // 重置到第一页
  list() // 重新加载数据
}

// 模拟数据（用于演示）
const getMockData = (): ElementData[] => {
  return [
    {
      elementId: '1',
      elementNum: '病史',
      elementCode: 'HX001',
      elementName: '高血压病史',
      elementalAbbreviation: '高血压',
      elementType: '下拉选择',
      elementalform: true,
      isDel: true
    },
    {
      elementId: '2',
      elementNum: '病史',
      elementCode: 'HX002',
      elementName: '糖尿病病史',
      elementalAbbreviation: '糖尿病',
      elementType: '下拉选择',
      elementalform: true,
      isDel: true
    },
    {
      elementId: '3',
      elementNum: '病史',
      elementCode: 'HX003',
      elementName: '冠心病病史',
      elementalAbbreviation: '冠心病',
      elementType: '平铺单选',
      elementalform: true,
      isDel: true
    },
    {
      elementId: '4',
      elementNum: '病史',
      elementCode: 'HX004',
      elementName: '手术史',
      elementalAbbreviation: '手术史',
      elementType: '文本输入',
      elementalform: false,
      isDel: true
    },
    {
      elementId: '5',
      elementNum: '病史',
      elementCode: 'HX005',
      elementName: '过敏史',
      elementalAbbreviation: '过敏史',
      elementType: '文本输入',
      elementalform: true,
      isDel: true
    }
  ];
}

// 初始化
onMounted(() => {
  list()
  listCategory()
})
</script>

<style scoped>
/* 页面整体容器 */
.element-management {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

/* 页面标题栏 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.breadcrumb {
  font-size: 14px;
  color: #6b7280;
}

/* 主内容区域 */
.main-content {
  display: flex;
  gap: 20px;
  min-height: calc(100vh - 140px);
}

/* 左侧分类侧边栏 */
.sidebar {
  width: 220px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.sidebar:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.sidebar-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  padding-bottom: 12px;
  border-bottom: 2px solid #e5e7eb;
}

.category-menu {
  border: none;
  background: transparent;
}

.category-menu .el-menu-item {
  padding: 10px 20px;
  margin: 4px 0;
  border-radius: 6px;
  transition: all 0.3s ease;
  color: #4b5563;
}

.category-menu .el-menu-item:hover {
  background-color: #f0f9ff;
  color: #1a5276;
}

.category-menu .el-menu-item.is-active {
  background-color: #e6f2ff;
  color: #1a5276;
  font-weight: bold;
}

/* 右侧内容面板 */
.content-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 搜索卡片 */
.search-card {
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

/* 搜索区域 */
.search-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.search-input {
  width: 240px;
}

.search-select {
  width: 120px;
}

.search-actions {
  display: flex;
  gap: 10px;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

/* 按钮样式 */
.create-btn,
.enable-btn,
.disable-btn,
.delete-btn,
.search-btn,
.reset-btn {
  transition: all 0.3s ease;
  border-radius: 6px;
}

.create-btn:hover,
.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.3);
}

.enable-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(34, 197, 94, 0.3);
}

.disable-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3);
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

.reset-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(107, 114, 128, 0.3);
}

/* 表格卡片 */
.table-card {
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  transition: all 0.3s ease;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table__header {
  background-color: #f5f7fa;
}

.el-table__row:hover {
  background-color: #f0f9ff;
}

.table-row-even {
  background-color: #ffffff;
}

.table-row-odd {
  background-color: #f9fafb;
}

/* 链接按钮样式 */
.edit-link:hover {
  color: #165dff;
}

.delete-link:hover {
  color: #f56c6c;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 20px 0 0 0;
}

.el-pagination {
  display: flex;
  align-items: center;
}

/* 弹窗样式 */
.dialog-form {
  padding: 10px 0;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-form-item__label {
  font-weight: 500;
  color: #374151;
}

.el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.el-dialog__header {
  background: linear-gradient(135deg, #165dff 0%, #0e42cc 100%);
  color: white;
  padding: 20px;
  margin: 0;
}

.el-dialog__title {
  color: white;
  font-weight: 600;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px;
  background-color: #f9fafb;
  border-top: 1px solid #e5e7eb;
}

.cancel-btn,
.save-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.save-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
  }
  
  .category-menu {
    display: flex;
    flex-wrap: wrap;
  }
  
  .category-menu .el-menu-item {
    flex: 1;
    min-width: 120px;
    text-align: center;
  }
}

@media (max-width: 768px) {
  .element-management {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
    padding: 16px;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .search-select {
    width: 100%;
  }
  
  .search-actions {
    justify-content: center;
  }
  
  .action-buttons {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .action-buttons .el-button {
    flex: 1;
    min-width: 80px;
  }
  
  .pagination-container {
    justify-content: center;
  }
  
  .el-dialog {
    width: 90% !important;
    margin: 10vh auto;
  }
}
</style>